import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:lz_app_core/utils/kd_storage.dart';
import 'package:lz_login/src/serve/kd_login_api.dart';
import 'package:lz_router/kd_router.dart';
import 'package:lz_ui/kd_ui.dart';
import 'package:lz_app_core/extension/kd_extension.dart';
import 'package:get/get.dart';
import '../router/kd_login_router.dart';
import '../widgets/kd_verification_code.dart';

/// 修改手机号
/// 传入参数 {"isChangeNewPhone": true}，
/// 不传则默认isChangeNewPhone=false
///
class KDChangePhonePage extends StatefulWidget {
  final bool? isChangeNewPhone;
  const KDChangePhonePage({super.key, this.isChangeNewPhone});

  @override
  State<KDChangePhonePage> createState() => _KDChangePhonePageState();
}

class _KDChangePhonePageState extends State<KDChangePhonePage> {
  /// obs
  var phoneErr = false.obs;
  var msgCodeErr = false.obs;

  /// 用户输入
  var phone = '';
  var hasGetCode = false;
  var code = '';
  bool checkProtocal = false;

  /// 是否是第二步，更换新号码
  var isChangeNewPhone = false;

  /// 输入手机号码
  late final TextEditingController _phoneController = TextEditingController();
  @override
  void initState() {
    super.initState();

    isChangeNewPhone = widget.isChangeNewPhone ?? false;
    // 第一步，取缓存手机
    if (!isChangeNewPhone) {
      phone = KDStorage.get<String>(KDStorageKey.phone.name) ?? '';
      _phoneController.text = phone;
    }
  }

  @override
  Widget build(BuildContext context) {
    return KDScaffold.scaffold(
      title: "修改手机号",
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.all(KD.size(32)),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              KDRedPointTitleWidget(
                  title: isChangeNewPhone ? "新的手机号" : "当前手机号"),
              _space(),

              Obx(
                () => KDFormInputWidget(
                  error: "请输入正确手机号",
                  isErr: phoneErr.value,
                  child: Row(
                    children: [
                      Expanded(
                          child: KDTextFiled.aLineInput(
                              controller: _phoneController,
                              maxLength: 11,
                              keyboardType: TextInputType.number,
                              key: const ObjectKey('phone'),
                              onChanged: (e) {
                                phone = e;
                                if (e.length == 11 && !e.isPhoneNumber) {
                                  phoneErr.value = true;
                                } else {
                                  phoneErr.value = false;
                                }
                              },
                              clearButtonMode: OverlayVisibilityMode.editing)),
                    ],
                  ),
                ),
              ),

              /// 验证码
              KDVerificationCodeWidget(
                phoneCall: () => phone,
                hasGetCode: (p0) => hasGetCode = p0,
                type: isChangeNewPhone ? 4 : 3,
                inputCode: (p0) {
                  code = p0;
                },
              ),

              /// 下一步
              KDBgWidget(
                bgColor: KDColor.main,
                margin: EdgeInsets.zero,
                height: KD.size(80),
                onTap: () {
                  next();
                },
                child: Center(
                    child: Text(
                  "下一步",
                  style: TextStyle(color: Colors.white, fontSize: KD.font(32)),
                )),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 按照dp
  Widget _space({double height = 16}) => SizedBox(
        height: KD.size(height),
      );

  next() async {
    if (!phone.isPhone) {
      phoneErr.value = true;
    }

    if (!hasGetCode) {
      DialogUtils.showToast("请先获取验证码");
      return;
    }

    if (hasGetCode && code.isEmpty) {
      DialogUtils.showToast("请先输入验证码");
      return;
    }

    if (hasGetCode && code.length != 4) {
      DialogUtils.showToast("验证码有误");
      return;
    }

    bool success = false;
    if (isChangeNewPhone) {
      success = await KDLoginApi.appUpdatePhone(phone: phone, authCode: code);
    } else {
      success = await KDLoginApi.appUpdatePhoneByCheckAuthCode(
          phone: phone, authCode: code);
    }

    if (success) {
      if (isChangeNewPhone) {
        DialogUtils.showToast("修改成功，请重新登陆");
        KDStorage.save(KDStorageKey.phone.name, phone);
        KDRouter.offAllNamed(KDLoginRouter.login);
      } else {
        // 老手机验证
        Get.to(const KDChangePhonePage(isChangeNewPhone: true));
      }
    }
  }
}
